﻿using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using WebStickyNotes.Contracts;
using WebStickyNotes.Data.Access;
using WebStickyNotes.Helpers;
using WebStickyNotes.Models;
using WebStickyNotes.Resources;

namespace WebStickyNotes.Controllers
{
    public class TaskProjectController : Controller
    {
        private readonly string _connectionType;
        private readonly string _connectionString;
        private readonly int _pageSize;

        private static readonly List<int> AllowedTaskRoleId = new List<int> { 1 };

        public TaskProjectController()
        {
            _connectionType = ConfigurationManager.AppSettings["ConnectionType"];
            _connectionString = ConfigurationManager.ConnectionStrings["WebStickyNotesData"].ConnectionString;
            _pageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]);
        }

        [HttpGet]
        [MustSignIn]
        public ActionResult Index(int? page)
        {
            var pageNumber = PagingHelper.GetPageNumber(page);

            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                var results = FilteredDataHelper.GetFilteredTaskProjectsForUser(supplier.DataAccess, currentUser);

                var model = new TaskProjectIndexModel
                {
                    TotalRecords = results.Count,
                    CurrentPage = pageNumber,
                    PageSize = _pageSize,
                    PagingLink = string.Format("{0}?page={1}", Request.Url.AbsolutePath, "{0}"),
                    TaskProjects = PagingHelper.GetPageOfResults(results, _pageSize, pageNumber),
                    CurrentUser = currentUser
                };

                return View(model);
            }
        }

        [HttpGet]
        [MustSignIn]
        public ActionResult Add()
        {
            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                var model = new EditTaskProjectModel
                                {
                                    Message = new Message(),
                                    Project = new TaskProject { Id = 0 }
                                };

                return View("Edit", model);
            }
        }

        [HttpPost]
        [MustSignIn]
        public ActionResult Add(EditTaskProjectModel model)
        {
            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                ValidateEditTaskProjectModel(model);

                if (ModelState.IsValid)
                {
                    var addSuccessModel = new AddSuccessModel
                    {
                        Id = supplier.DataAccess.SaveTaskProject(model.Project),
                        Action = "Edit",
                        Controller = "TaskProject",
                        ViewItems = Labels.Projects,
                        ViewAction = "TaskProjects",
                        Message = new Message
                        {
                            Class = "okay",
                            Text = Labels.SavedOkay
                        }
                    };

                    // Audit
                    AuditHelper.AuditAction(supplier.DataAccess, "Add", model.Project, currentUser.Id);

                    // ReSharper disable Asp.NotResolved
                    return View(addSuccessModel);
                    // ReSharper restore Asp.NotResolved
                }

                model.Message = new Message { Text = Labels.PleaseCorrectErrors, Class = "error" };

                return View("Edit", model);
            }
        }

        [HttpGet]
        [MustSignIn]
        public ActionResult Edit(int id)
        {
            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                var model = new EditTaskProjectModel
                                {
                                    Message = new Message(),
                                    Project = supplier.DataAccess.GetTaskProject(id)
                                };

                return View(model);
            }
        }

        [HttpPost]
        [MustSignIn]
        public ActionResult Edit(EditTaskProjectModel model)
        {
            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                ValidateEditTaskProjectModel(model);

                if (ModelState.IsValid)
                {
                    supplier.DataAccess.SaveTaskProject(model.Project);
                    model.Message = new Message { Text = Labels.SavedOkay, Class = "okay" };

                    // Audit
                    AuditHelper.AuditAction(supplier.DataAccess, "Edit", model.Project, currentUser.Id);
                }
                else
                {
                    model.Message = new Message { Text = Labels.PleaseCorrectErrors, Class = "error" };
                }

                return View(model);
            }
        }

        [HttpGet]
        [MustSignIn]
        public ActionResult Delete(int id)
        {
            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                var model = new DeleteTaskProjectModel
                {
                    Project = supplier.DataAccess.GetTaskProject(id),
                    ShowButton = true,
                    Message = new Message
                    {
                        Text = Labels.TextAreYouSureYouWantToDelete,
                        Class = "error"
                    }
                };

                var projectCount = supplier.DataAccess.GetStreamsByProject(id).Count;

                if (projectCount > 0)
                {
                    model.ShowButton = false;
                    model.Message.Text = string.Format(Labels.TextCannotDelete, projectCount);
                    model.Message.Class = "error";
                }

                return View(model);
            }
        }

        [HttpPost]
        [MustSignIn]
        public ActionResult Delete(bool confirm, int id)
        {
            using (var supplier = new Supplier(_connectionType, _connectionString))
            {
                var currentUser = supplier.DataAccess.GetTaskPerson(SecurityHelper.GetSignedInUserId());
                if (!AllowedTaskRoleId.Contains(currentUser.TaskRoleId))
                {
                    return RedirectToAction("AccessDenied", "Home", new { address = HttpContext.Request.Url.AbsoluteUri });
                }

                var model = new DeleteTaskProjectModel
                {
                    Project = supplier.DataAccess.GetTaskProject(id),
                    ShowButton = false,
                    Message = new Message
                    {
                        Text = Labels.DeletedOkay,
                        Class = "okay"
                    }
                };

                supplier.DataAccess.DeleteTaskProject(id);

                // Audit
                AuditHelper.AuditAction(supplier.DataAccess, "Delete", model.Project, currentUser.Id);

                return View(model);
            }
        }

        private void ValidateEditTaskProjectModel(EditTaskProjectModel model)
        {
            if (string.IsNullOrEmpty(model.Project.Title))
            {
                ModelState.AddModelError("Project.Title", Labels.PleaseEnterTitle);
            }
        }
    }
}